// MySQL后端API客户端

interface ApiResponse<T = any> {
  data?: T
  error?: string
  message?: string
}

interface User {
  id: string
  email: string
  emailVerified: boolean
  createdAt: string
}

interface UserProfile {
  id: string
  nickname?: string
  avatarUrl?: string
  createdAt: string
  updatedAt: string
}

interface UserSettings {
  id: string
  theme: 'LIGHT' | 'DARK' | 'AUTO'
  searchEngine: 'GOOGLE' | 'BING' | 'BAIDU' | 'DUCKDUCKGO'
  backgroundType: 'GRADIENT' | 'IMAGE' | 'COLOR'
  backgroundValue?: string
  showBookmarks: boolean
  showWeather: boolean
  showTime: boolean
  language: string
  createdAt: string
  updatedAt: string
}

interface Bookmark {
  id: string
  title: string
  url: string
  iconUrl?: string
  category: string
  sortOrder: number
  createdAt: string
  updatedAt: string
}

interface TokenPair {
  accessToken: string
  refreshToken: string
}

class ApiClient {
  private baseURL: string
  private accessToken: string | null = null
  private refreshToken: string | null = null

  // @ts-ignore
  constructor(baseURL: string =  '/api') {
    this.baseURL = baseURL
    this.loadTokensFromStorage()
  }

  // 从localStorage加载令牌
  private loadTokensFromStorage() {
    if (typeof window !== 'undefined') {
      this.accessToken = localStorage.getItem('accessToken')
      this.refreshToken = localStorage.getItem('refreshToken')
    }
  }

  // 保存令牌到localStorage
  private saveTokensToStorage(tokens: TokenPair) {
    if (typeof window !== 'undefined') {
      localStorage.setItem('accessToken', tokens.accessToken)
      localStorage.setItem('refreshToken', tokens.refreshToken)
      this.accessToken = tokens.accessToken
      this.refreshToken = tokens.refreshToken
    }
  }

  // 清除令牌
  private clearTokens() {
    if (typeof window !== 'undefined') {
      localStorage.removeItem('accessToken')
      localStorage.removeItem('refreshToken')
      this.accessToken = null
      this.refreshToken = null
    }
  }

  // 发送HTTP请求
  private async request<T>(
    endpoint: string,
    options: RequestInit = {}
  ): Promise<T> {
    const url = `${this.baseURL}${endpoint}`
    const headers: HeadersInit = {
      'Content-Type': 'application/json',
      ...options.headers
    }

    // 添加认证头
    if (this.accessToken) {
      // @ts-ignore
      headers.Authorization = `Bearer ${this.accessToken}`
    }

    try {
      const response = await fetch(url, {
        ...options,
        headers
      })

      // 检查是否有新的访问令牌
      const newAccessToken = response.headers.get('X-New-Access-Token')
      if (newAccessToken) {
        this.accessToken = newAccessToken
        if (typeof window !== 'undefined') {
          localStorage.setItem('accessToken', newAccessToken)
        }
      }

      const data = await response.json()

      if (!response.ok) {
        // 如果是401错误，尝试刷新令牌
        if (response.status === 401 && this.refreshToken) {
          const refreshed = await this.refreshAccessToken()
          if (refreshed) {
            // 重新发送原请求
            return this.request<T>(endpoint, options)
          }
        }
        throw new Error(data.error || `HTTP ${response.status}`)
      }

      return data
    } catch (error) {
      console.error('API请求失败:', error)
      throw error
    }
  }

  // 刷新访问令牌
  private async refreshAccessToken(): Promise<boolean> {
    if (!this.refreshToken) return false

    try {
      const response = await fetch(`${this.baseURL}/auth/refresh`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          refreshToken: this.refreshToken
        })
      })

      if (response.ok) {
        const data = await response.json()
        this.saveTokensToStorage(data.tokens)
        return true
      } else {
        // 刷新失败，清除令牌
        this.clearTokens()
        return false
      }
    } catch (error) {
      console.error('刷新令牌失败:', error)
      this.clearTokens()
      return false
    }
  }

  // 认证相关方法
  async register(email: string, password: string, nickname?: string) {
    const response = await this.request<{
      user: User
      tokens: TokenPair
      message: string
    }>('/auth/register', {
      method: 'POST',
      body: JSON.stringify({ email, password, nickname })
    })

    if (response.tokens) {
      this.saveTokensToStorage(response.tokens)
    }

    return response
  }

  async login(email: string, password: string) {
    const response = await this.request<{
      user: User
      tokens: TokenPair
      message: string
    }>('/auth/login', {
      method: 'POST',
      body: JSON.stringify({ email, password })
    })

    if (response.tokens) {
      this.saveTokensToStorage(response.tokens)
    }

    return response
  }

  async logout() {
    try {
      await this.request('/auth/logout', {
        method: 'POST',
        body: JSON.stringify({
          refreshToken: this.refreshToken
        })
      })
    } finally {
      this.clearTokens()
    }
  }

  async getCurrentUser() {
    return this.request<{
      user: User & {
        profile: UserProfile
        settings: UserSettings
      }
    }>('/auth/me')
  }

  // 用户数据相关方法
  async getUserProfile() {
    return this.request<{ profile: UserProfile }>('/user/profile')
  }

  async updateUserProfile(updates: Partial<UserProfile>) {
    return this.request<{
      profile: UserProfile
      message: string
    }>('/user/profile', {
      method: 'PUT',
      body: JSON.stringify(updates)
    })
  }

  async getUserSettings() {
    return this.request<{ settings: UserSettings }>('/user/settings')
  }

  async updateUserSettings(updates: Partial<UserSettings>) {
    return this.request<{
      settings: UserSettings
      message: string
    }>('/user/settings', {
      method: 'PUT',
      body: JSON.stringify(updates)
    })
  }

  // 批量获取用户数据（优化版本）
  async getUserData() {
    return this.request<{
      profile: UserProfile
      settings: UserSettings
    }>('/user/data')
  }

  // 书签相关方法
  async getBookmarks(options?: {
    category?: string
    search?: string
    limit?: number
    offset?: number
  }) {
    const params = new URLSearchParams()
    if (options?.category) params.append('category', options.category)
    if (options?.search) params.append('search', options.search)
    if (options?.limit) params.append('limit', options.limit.toString())
    if (options?.offset) params.append('offset', options.offset.toString())

    const query = params.toString() ? `?${params.toString()}` : ''
    return this.request<{
      bookmarks: Bookmark[]
      total: number
    }>(`/bookmarks${query}`)
  }

  async createBookmark(bookmark: {
    title: string
    url: string
    iconUrl?: string
    category?: string
  }) {
    return this.request<{
      bookmark: Bookmark
      message: string
    }>('/bookmarks', {
      method: 'POST',
      body: JSON.stringify(bookmark)
    })
  }

  async updateBookmark(id: string, updates: Partial<Bookmark>) {
    return this.request<{
      bookmark: Bookmark
      message: string
    }>(`/bookmarks/${id}`, {
      method: 'PUT',
      body: JSON.stringify(updates)
    })
  }

  async deleteBookmark(id: string) {
    return this.request<{ message: string }>(`/bookmarks/${id}`, {
      method: 'DELETE'
    })
  }

  async updateBookmarkOrder(bookmarks: Array<{ id: string; sortOrder: number }>) {
    return this.request<{ message: string }>('/bookmarks/order', {
      method: 'PUT',
      body: JSON.stringify({ bookmarks })
    })
  }

  async getBookmarkCategories() {
    return this.request<{
      categories: Array<{ name: string; count: number }>
    }>('/bookmarks/categories')
  }

  // 工具方法
  isAuthenticated(): boolean {
    return !!this.accessToken
  }

  getAccessToken(): string | null {
    return this.accessToken
  }

  // 健康检查
  async healthCheck() {
    return fetch(`${this.baseURL.replace('/api', '')}/health`)
      .then(res => res.json())
  }
}

// 导出单例实例
export const apiClient = new ApiClient()
export default apiClient

// 导出类型
export type {
  User,
  UserProfile,
  UserSettings,
  Bookmark,
  TokenPair,
  ApiResponse
}